package poketrade.managers;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import poketrade.entities.User;
import poketrade.utils.SHA1;

@Stateless
public class UserManager {
	
	@PersistenceContext(name="Poketrade")
	EntityManager em;
	
	public User handleLogin(String pseudo, String password)
	{
		// TODO Add a salt based authentication
		@SuppressWarnings("unchecked")
		List<User> l = em.createNamedQuery("queryLogin")
		.setParameter("pseudo", pseudo)
		.setParameter("password", SHA1.encode(password))
		.getResultList();
		if (l.size() == 0)
			return null;
		else
			return l.get(0);
	}
	
	public List<String> getAddressList()
	{
		@SuppressWarnings("unchecked")
		List<User> l = em.createNamedQuery("queryAllUsers").getResultList();
		List<String> addresses = new ArrayList<String>();
		for (User u : l)
			addresses.add(u.getAdresse());
		return addresses;
	}
	
	public User subscribe(User u)
	{
		em.persist(u);
		return u;
	}
	
	public void deleteUser(long id)
	{
		User linkedUser = em.find(User.class, id);
		em.remove(linkedUser);
	}
	
	public User upgradeMember(long id)
	{
		User linkedUser = em.find(User.class, id);
		linkedUser.setSolde(linkedUser.getSolde() - 200.f);
		linkedUser.setPremium(true);
		return linkedUser;
	}

	public User updateUser(long id, String email, String adresse, String ville, String dep) {
		User u = em.find(User.class, id);
		u.setEmail(email);
		u.setAdresse(adresse);
		u.setVille(ville);
		u.setDepartement(dep);
		return u;
	}
}
